<template>
  <div class="user-profile">
    <div v-if="loading" class="loading">
      <div class="spinner"></div>
    </div>
    
    <div v-else-if="userInfo" class="user-info-container">
      <!-- 用户头像 -->
      <div class="avatar-section">
        <div class="avatar-wrapper" @click="triggerFileInput">
          <img :src="userInfo.avatarUrl" alt="用户头像" class="avatar" />
          <div class="avatar-overlay">
            <span class="upload-text">点击上传</span>
          </div>
          <input 
            ref="fileInputRef" 
            type="file" 
            accept="image/jpeg,image/jpg,image/png,image/gif,image/webp,image/svg+xml"
            @change="handleFileSelect"
            style="display: none"
          />
        </div>
        <div v-if="uploading" class="upload-progress">
          <div class="progress-bar" :style="{ width: uploadProgress + '%' }"></div>
          <span class="progress-text">{{ uploadProgress }}%</span>
        </div>
      </div>
      
      <!-- 用户信息 -->
      <div class="info-section">
        <div class="info-item">
          <span class="label">IP地址:</span>
          <span class="value">{{ userInfo.ipAddress }}</span>
        </div>
        <div class="info-item">
          <span class="label">总转换次数:</span>
          <span class="value highlight">{{ userInfo.totalConversions }}</span>
        </div>
      </div>
    </div>
    
    <div v-else class="error">
      <p>无法加载用户信息</p>
    </div>
    
    <!-- 头像裁剪弹窗 -->
    <AvatarCropper
      v-model:visible="showCropper"
      :image-file="selectedFile"
      @save="handleCropSave"
      @cancel="handleCropCancel"
    />
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { getCurrentUser, uploadAvatar } from '@/api/user'
import AvatarCropper from './AvatarCropper.vue'
import { toastSuccess, toastError } from '@/utils/toast'

const userInfo = ref(null)
const loading = ref(true)
const uploading = ref(false)
const uploadProgress = ref(0)
const fileInputRef = ref(null)
const showCropper = ref(false)
const selectedFile = ref(null)

// 加载用户信息
const loadUserInfo = async () => {
  try {
    loading.value = true
    const response = await getCurrentUser()
    userInfo.value = response.data
  } catch (error) {
    console.error('加载用户信息失败:', error)
  } finally {
    loading.value = false
  }
}

// 触发文件选择
const triggerFileInput = () => {
  fileInputRef.value?.click()
}

// 处理文件选择
const handleFileSelect = (event) => {
  const file = event.target.files[0]
  if (!file) return
  
  // 验证文件类型
  const allowedTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'image/webp', 'image/svg+xml']
  if (!allowedTypes.includes(file.type)) {
    toastError('不支持的文件格式，请选择 JPG、PNG、GIF、WebP 或 SVG 格式的图片')
    // 清空文件输入框
    if (fileInputRef.value) {
      fileInputRef.value.value = ''
    }
    return
  }
  
  // 验证文件大小（5MB）
  if (file.size > 5 * 1024 * 1024) {
    toastError('文件大小不能超过5MB')
    // 清空文件输入框
    if (fileInputRef.value) {
      fileInputRef.value.value = ''
    }
    return
  }
  
  // 显示裁剪弹窗
  selectedFile.value = file
  showCropper.value = true
}

// 处理裁剪保存
const handleCropSave = async (croppedFile) => {
  try {
    uploading.value = true
    uploadProgress.value = 0
    
    const response = await uploadAvatar(croppedFile, (progress) => {
      uploadProgress.value = progress
    })
    
    // 更新用户信息
    userInfo.value = response.data
    toastSuccess('头像上传成功！')
  } catch (error) {
    console.error('上传头像失败:', error)
    toastError('上传失败: ' + error.message)
  } finally {
    uploading.value = false
    uploadProgress.value = 0
    selectedFile.value = null
    // 清空文件输入框，以便可以重复选择同一个文件
    if (fileInputRef.value) {
      fileInputRef.value.value = ''
    }
  }
}

// 处理裁剪取消
const handleCropCancel = () => {
  selectedFile.value = null
  // 清空文件输入框
  if (fileInputRef.value) {
    fileInputRef.value.value = ''
  }
}

// 组件挂载时加载用户信息
onMounted(() => {
  loadUserInfo()
})

// 暴露刷新方法供父组件调用
defineExpose({
  refresh: loadUserInfo
})
</script>

<style scoped>
.user-profile {
  padding: 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 12px;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
  color: white;
}

.loading {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 120px;
}

.spinner {
  width: 40px;
  height: 40px;
  border: 4px solid rgba(255, 255, 255, 0.3);
  border-top-color: white;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}

.user-info-container {
  display: flex;
  align-items: center;
  gap: 20px;
}

.avatar-section {
  flex-shrink: 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
}

.avatar-wrapper {
  position: relative;
  cursor: pointer;
  transition: transform 0.2s;
}

.avatar-wrapper:hover {
  transform: scale(1.05);
}

.avatar-wrapper:hover .avatar-overlay {
  opacity: 1;
}

.avatar {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  background: white;
  padding: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  object-fit: cover;
  display: block;
}

.avatar-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  border-radius: 50%;
  background: rgba(0, 0, 0, 0.6);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.2s;
  pointer-events: none;
}

.upload-icon {
  font-size: 24px;
  margin-bottom: 4px;
}

.upload-text {
  font-size: 10px;
  color: white;
  font-weight: 600;
}

.upload-progress {
  width: 80px;
  height: 4px;
  background: rgba(255, 255, 255, 0.3);
  border-radius: 2px;
  overflow: hidden;
  position: relative;
}

.progress-bar {
  height: 100%;
  background: white;
  transition: width 0.3s;
  border-radius: 2px;
}

.progress-text {
  position: absolute;
  top: -20px;
  left: 50%;
  transform: translateX(-50%);
  font-size: 11px;
  color: white;
  white-space: nowrap;
}

.info-section {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.info-item {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
}

.label {
  font-weight: 500;
  opacity: 0.9;
  min-width: 90px;
}

.value {
  font-weight: 600;
  font-size: 15px;
}

.value.highlight {
  font-size: 18px;
  color: #ffd700;
}

.error {
  text-align: center;
  padding: 20px;
  color: rgba(255, 255, 255, 0.8);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .user-profile {
    padding: 15px;
  }
  
  .user-info-container {
    flex-direction: column;
    text-align: center;
  }
  
  .avatar {
    width: 60px;
    height: 60px;
  }
  
  .upload-progress {
    width: 60px;
  }
  
  .info-section {
    width: 100%;
  }
  
  .info-item {
    flex-direction: column;
    gap: 4px;
  }
  
  .label {
    min-width: auto;
    font-size: 12px;
  }
  
  .value {
    font-size: 14px;
  }
}
</style>

